<?php
/**
 * NDbCommand helper class.
 * This class provide some common use database command line.
 *
 * @package    Core / quangnghia
 * @author     Nguyen Quang Nghia @ ngaycuoithang2@gmail.com
 */
class NDbCommand {
	
	/** Add this to Controller **/
	/*
	public function actionToggleVisible()
	{
		NDbCommand::toggle($tableName, $_POST['multiselect'],'visible');
	}
	*/
	/* Toogle visible column, 
	* we can duplicate and change column name to something similar as active, disable, allow... 
	*/
	public static function toggle($tableName, $ids, $column_to_toggle = 'visible')
	{
		if(isset($ids))
		{
			$sql = "UPDATE {$tableName} SET {$column_to_toggle}=1-{$column_to_toggle} WHERE id IN(".implode(',',$ids).")";
			$command = Yii::app()->db->createCommand($sql);
			$affected_rows = $command->execute();
			Yii::app()->user->setFlash('success','Đã cập nhật: ' . $affected_rows);
			return true;
		}
		return false;
	}
	
	/** Add this to Controller **/
	/*
	public function actionUpdateDisplayOrder()
	{
		NDbCommand::updateOrder($tableName, 'sort');
	}
	*/
	public static function updateOrder($tableName, $order_column_name = 'sort')
	{
		$ids = $_POST[$order_column_name];
		if(isset($ids))
		{
			$affected_rows = 0
			foreach ($ids as $key => $value) {
				$sql = "UPDATE {$tableName} SET {$order_column_name}=:value WHERE id=:id";
				$command = Yii::app()->db->createCommand($sql);
				$$affected_rows += $command->execute(array(':value'=>$value,':id'=>$key));
			}
			Yii::app()->user->setFlash('success','Đã cập nhật: ' . $affected_rows);
			return true;
		}
		return false;
	}
	
	/*
	// Need to be updated parameters same as above
	public function actionDeleteAll()
	{
		if(isset($_POST['multiselect']))
		{
			$sql = "DELETE FROM {{user}} WHERE id IN(".implode(',',$_POST['multiselect']).")";
			$command = Yii::app()->db->createCommand($sql);
			$affected_rows = $command->execute();
			Yii::app()->user->setFlash('message',Yii::t('backend','{obj} record(s) deleted.', array('{obj}'=>$affected_rows)));
			
			// $model = Photo::model()->findAllByPk($_POST['multiselect']);
			// foreach ($model as $data) {
				// $data->delete();
			// }
		}
		$this->redirect(array('admin'));
	}
	*/
	
}